package com.example.mymvvmdemo.net.model;

import androidx.annotation.NonNull;

import com.example.mymvvmdemo.api.API;
import com.example.mymvvmdemo.retrofit.RetrofitManager;
import com.example.mymvvmdemo.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * 用来请求只携带一个body的post请求
 */
public class PutBodyModel extends BaseModel {

    private IModel.PutBodyModel putBodyModel;

    public PutBodyModel(IModel.PutBodyModel putBodyModel) {
        this.putBodyModel = putBodyModel;
    }

    public void startLoadPutBody(String url, String auth_token, HashMap<String, String> hashMap, String type) {

        // 创建JSON对象来确保正确的格式
        JSONObject jsonObject = new JSONObject();
        try {
            for (String key : hashMap.keySet()) {
                if (key.equals("tag_ids")) {
                    // 将tag_ids转换为JSON数组
                    String tagIdsStr = hashMap.get(key);
                    JSONArray tagIdsArray = new JSONArray(tagIdsStr);
                    jsonObject.put(key, tagIdsArray);
                } else {
                    jsonObject.put(key, hashMap.get(key));
                }
            }
        } catch (Exception e) {
            LogUtils.e("创建JSON对象时出错: " + e.getMessage());
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());

        // Format the auth token with Bearer prefix
        String formattedToken = "Bearer " + auth_token;

        RetrofitManager.getInstance().getRetrofit().create(API.class).loadPutBody(
                        url, formattedToken, body, hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody responseBody) {

                        try {
                            String result = responseBody.string();
                            //判断请求网络是否异常
                            if (isNetWorkError(result)) {
                                putBodyModel.loadPutBodyNetWorkError(result);
                                return;
                            }

                            JSONObject jsonObject = new JSONObject(result);
                            int code = jsonObject.getInt("code");
                            //检查是否账号异常（被挤或者token异常)
//                            boolean isError = CheckOutUtils.checkErrorCode(code);
//                            if (isError) {
//                                putBodyModel.loadPutBodyAccountError(code);
//                            } else {
                            putBodyModel.loadPutBodySuccess(result, type, code);
//                            }

                        } catch (Exception e) {
                            putBodyModel.loadPutBodyFail(e.getMessage(), type);
                            LogUtils.e(e.getMessage());
                        }


                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //判断请求网络是否异常
                        if (isNetWorkError(e.getMessage())) {
                            putBodyModel.loadPutBodyNetWorkError(e.getMessage());
                            return;
                        }
                        putBodyModel.loadPutBodyFail(e.getMessage(), type);
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

}
